package com.cash.app.utils.extra.tools

import java.io.BufferedReader
import java.io.FileNotFoundException
import java.io.FileReader
import java.io.IOException

object CpuUtils {
    val cpuName: String?
        get() {
            try {
                val fr = FileReader("/proc/cpuinfo")
                val br = BufferedReader(fr)
                val text = br.readLine()
                val array =
                    text.split(":\\s+".toRegex(), limit = 2).toTypedArray()
                return array[1]
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return null
        }

    val maxCpuFreq: String
        get() {
            var result = ""
            val cmd: ProcessBuilder
            try {
                val args = arrayOf(
                    "/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"
                )
                cmd = ProcessBuilder(*args)
                val process = cmd.start()
                val `in` = process.inputStream
                val re = ByteArray(24)
                while (`in`.read(re) != -1) {
                    result = result + String(re)
                }
                `in`.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
                result = "N/A"
            }
            return result.trim { it <= ' ' }
        }


    val minCpuFreq: String
        get() {
            var result = ""
            val cmd: ProcessBuilder
            try {
                val args = arrayOf(
                    "/system/bin/cat",
                    "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq"
                )
                cmd = ProcessBuilder(*args)
                val process = cmd.start()
                val `in` = process.inputStream
                val re = ByteArray(24)
                while (`in`.read(re) != -1) {
                    result = result + String(re)
                }
                `in`.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
                result = "N/A"
            }
            return result.trim { it <= ' ' }
        }

    val curCpuFreq: String
        get() {
            var result = "N/A"
            try {
                val fr = FileReader(
                    "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"
                )
                val br = BufferedReader(fr)
                val text = br.readLine()
                result = text.trim { it <= ' ' }
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
            } catch (e: IOException) {
                e.printStackTrace()
            }
            return result
        }
}
